package com.hzw.saas.service.schedule.service;

import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Sets;
import com.hzw.saas.api.schedule.UserScheduleTagRelService;
import com.hzw.saas.common.util.SnowFlakeUtil;
import com.hzw.saas.service.schedule.mapper.UserScheduleTagRelMapper;
import com.hzw.saas.service.schedule.model.UserScheduleTagRel;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class UserScheduleTagRelServiceImpl extends ServiceImpl<UserScheduleTagRelMapper, UserScheduleTagRel> implements UserScheduleTagRelService, IService<UserScheduleTagRel> {

    @Override
    public void addUserScheduleTagRel(String scheduleId, Collection<String> tagIds) {
        if (CollectionUtils.isEmpty(tagIds)) {
            return;
        }
        List<UserScheduleTagRel> scheduleTagRelList = tagIds.stream()
                .distinct()
                .map(tagId -> {
                    UserScheduleTagRel userScheduleTagRel = new UserScheduleTagRel()
                            .setScheduleId(scheduleId)
                            .setTagId(tagId);
                    userScheduleTagRel.setPid(SnowFlakeUtil.nextIdStr());
                    return userScheduleTagRel;
                })
                .collect(Collectors.toList());
        super.saveBatch(scheduleTagRelList);
    }

    @Override
    public void updateUserScheduleTagRel(String scheduleId, Collection<String> tagIds) {
        if (Objects.isNull(tagIds)) {
            return;
        }
        Set<String> dbSet = super.lambdaQuery()
                .eq(UserScheduleTagRel::getScheduleId, scheduleId)
                .list()
                .stream()
                .map(UserScheduleTagRel::getTagId)
                .collect(Collectors.toSet());
        Set<String> paramSet = CollectionUtils.isEmpty(tagIds) ? Sets.newHashSet() : new HashSet<>(tagIds);
        Sets.SetView<String> deleteSet = Sets.difference(dbSet, paramSet);
        Sets.SetView<String> addSet = Sets.difference(paramSet, dbSet);
        if (!CollectionUtils.isEmpty(deleteSet)) {
            super.lambdaUpdate()
                    .eq(UserScheduleTagRel::getScheduleId, scheduleId)
                    .in(UserScheduleTagRel::getTagId, deleteSet)
                    .remove();
        }
        if (!CollectionUtils.isEmpty(addSet)) {
            addUserScheduleTagRel(scheduleId, addSet);
        }
    }

    @Override
    public void deleteByTagIds(Collection<String> tagIds) {
        if (!CollectionUtils.isEmpty(tagIds)) {
            super.lambdaUpdate()
                    .in(UserScheduleTagRel::getTagId, tagIds)
                    .remove();
        }
    }
}
